<!-- 历史列表展示 -->
<!-- 筛选功能 -->
<!-- 复习功能 --> 

<template>
  <view class="history-page">
    <!-- 顶部导航 -->
    <view class="nav-bar">
      <text class="title">历史记录</text>
      <button class="edit-btn" @click="toggleEdit">
        {{ isEdit ? '完成' : '编辑' }}
      </button>
    </view>

    <!-- 筛选区域 -->
    <view class="filter-bar">
      <view class="filter-item" @click="showDifficultyPicker">
        <text>难度</text>
        <text class="value">{{ difficultyText }}</text>
        <text class="iconfont icon-arrow-down"></text>
      </view>
      <view class="filter-item" @click="showDatePicker">
        <text>时间范围</text>
        <text class="value">{{ dateRangeText }}</text>
        <text class="iconfont icon-arrow-down"></text>
      </view>
    </view>

    <!-- 历史列表 -->
    <scroll-view 
      class="history-list"
      scroll-y
      @scrolltolower="loadMore"
      :refresher-enabled="true"
      :refresher-triggered="isRefreshing"
      @refresherrefresh="onRefresh"
    >
      <view 
        v-for="item in historyList" 
        :key="item.id"
        class="history-item"
      >
        <!-- 选择框 -->
        <view v-if="isEdit" class="checkbox" @click="toggleSelect(item)">
          <text 
            class="iconfont" 
            :class="selectedIds.includes(item.id) ? 'icon-checkbox-checked' : 'icon-checkbox'"
          ></text>
        </view>

        <!-- 基础字 -->
        <view class="base-char">
          <text>{{ item.baseChars[0] }}</text>
        </view>

        <!-- 内容区 -->
        <view class="content">
          <view class="title-row">
            <text class="title">{{ item.baseChars.join('') }}</text>
            <text 
              class="difficulty-tag"
              :class="`difficulty-${item.difficulty}`"
            >
              {{ getDifficultyText(item.difficulty) }}
            </text>
          </view>
          <text class="date">{{ formatDate(item.createdAt) }}</text>
        </view>

        <!-- 复习按钮 -->
        <button 
          v-if="!isEdit"
          class="review-btn"
          @click="handleReview(item)"
        >
          <text class="iconfont icon-redo"></text>
          复习
        </button>
      </view>

      <!-- 加载状态 -->
      <view v-if="loading" class="loading">
        <text class="iconfont icon-loading"></text>
        加载中...
      </view>
      <view v-if="!loading && !hasMore" class="no-more">
        没有更多记录了
      </view>
    </scroll-view>

    <!-- 编辑模式底部栏 -->
    <view v-if="isEdit" class="edit-bar">
      <view class="select-all" @click="toggleSelectAll">
        <text 
          class="iconfont"
          :class="isAllSelected ? 'icon-checkbox-checked' : 'icon-checkbox'"
        ></text>
        <text>全选</text>
      </view>
      <button class="delete-btn" @click="handleDelete">
        删除({{ selectedIds.length }})
      </button>
    </view>

    <!-- 难度选择器 -->
    <uni-popup ref="difficultyPopup" type="bottom">
      <view class="picker-content">
        <view class="picker-header">
          <text>选择难度</text>
          <button @click="closeDifficultyPicker">完成</button>
        </view>
        <picker-view 
          :value="[difficultyIndex]"
          @change="onDifficultyChange"
          class="picker-view"
        >
          <picker-view-column>
            <view class="picker-item" v-for="item in difficultyOptions" :key="item.value">
              {{ item.label }}
            </view>
          </picker-view-column>
        </picker-view>
      </view>
    </uni-popup>

    <!-- 日期选择器 -->
    <uni-popup ref="datePopup" type="bottom">
      <view class="picker-content">
        <view class="picker-header">
          <text>选择时间范围</text>
          <button @click="closeDatePicker">完成</button>
        </view>
        <picker-view 
          :value="[dateRangeIndex]"
          @change="onDateRangeChange"
          class="picker-view"
        >
          <picker-view-column>
            <view class="picker-item" v-for="item in dateRangeOptions" :key="item.value">
              {{ item.label }}
            </view>
          </picker-view-column>
        </picker-view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue'
import { getExerciseHistory } from '@/api/exercise'
import { formatDate } from '@/utils'

// 筛选选项
const difficultyOptions = [
  { label: '全部难度', value: 0 },
  { label: '容易', value: 1 },
  { label: '中等', value: 2 },
  { label: '较难', value: 3 }
]

const dateRangeOptions = [
  { label: '全部时间', value: 0 },
  { label: '最近7天', value: 7 },
  { label: '最近30天', value: 30 },
  { label: '最近90天', value: 90 }
]

// 响应式状态
const isEdit = ref(false)
const selectedIds = ref([])
const historyList = ref([])
const loading = ref(false)
const hasMore = ref(true)
const isRefreshing = ref(false)
const page = ref(1)
const pageSize = ref(20)
const difficultyIndex = ref(0)
const dateRangeIndex = ref(0)

// 计算属性
const difficultyText = computed(() => {
  return difficultyOptions[difficultyIndex.value].label
})

const dateRangeText = computed(() => {
  return dateRangeOptions[dateRangeIndex.value].label
})

const isAllSelected = computed(() => {
  return selectedIds.value.length === historyList.value.length
})

// 获取历史记录
const getHistory = async (isRefresh = false) => {
  if (loading.value) return
  
  try {
    loading.value = true
    
    const params = {
      page: isRefresh ? 1 : page.value,
      size: pageSize.value,
      difficulty: difficultyOptions[difficultyIndex.value].value,
      days: dateRangeOptions[dateRangeIndex.value].value
    }
    
    const { list, total } = await getExerciseHistory(params)
    
    if (isRefresh) {
      historyList.value = list
      page.value = 1
    } else {
      historyList.value.push(...list)
      page.value++
    }
    
    hasMore.value = historyList.value.length < total
  } catch (error) {
    uni.showToast({
      title: error.message || '加载失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
    isRefreshing.value = false
  }
}

// 下拉刷新
const onRefresh = async () => {
  isRefreshing.value = true
  await getHistory(true)
}

// 加载更多
const loadMore = () => {
  if (hasMore.value && !loading.value) {
    getHistory()
  }
}

// 编辑相关
const toggleEdit = () => {
  isEdit.value = !isEdit.value
  selectedIds.value = []
}

const toggleSelect = (item) => {
  const index = selectedIds.value.indexOf(item.id)
  if (index > -1) {
    selectedIds.value.splice(index, 1)
  } else {
    selectedIds.value.push(item.id)
  }
}

const toggleSelectAll = () => {
  if (isAllSelected.value) {
    selectedIds.value = []
  } else {
    selectedIds.value = historyList.value.map(item => item.id)
  }
}

// 删除选中项
const handleDelete = () => {
  if (selectedIds.value.length === 0) {
    return uni.showToast({
      title: '请选择要删除的记录',
      icon: 'none'
    })
  }
  
  uni.showModal({
    title: '提示',
    content: '确定要删除选中的记录吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          await deleteExercise(selectedIds.value)
          await getHistory(true)
          toggleEdit()
        } catch (error) {
          uni.showToast({
            title: error.message || '删除失败',
            icon: 'none'
          })
        }
      }
    }
  })
}

// 复习
const handleReview = (item) => {
  uni.navigateTo({
    url: `/pages/study/index?id=${item.id}`
  })
}

// 筛选器相关
const difficultyPopup = ref(null)
const datePopup = ref(null)

const showDifficultyPicker = () => {
  difficultyPopup.value.open()
}

const closeDifficultyPicker = () => {
  difficultyPopup.value.close()
}

const onDifficultyChange = (e) => {
  difficultyIndex.value = e.detail.value[0]
  getHistory(true)
}

const showDatePicker = () => {
  datePopup.value.open()
}

const closeDatePicker = () => {
  datePopup.value.close()
}

const onDateRangeChange = (e) => {
  dateRangeIndex.value = e.detail.value[0]
  getHistory(true)
}

// 工具函数
const getDifficultyText = (difficulty) => {
  return difficultyOptions.find(item => item.value === difficulty)?.label || '未知'
}

// 初始化
onMounted(() => {
  getHistory()
})
</script>

<style lang="scss" scoped>
.history-page {
  min-height: 100vh;
  background: #f5f7fa;
  padding-bottom: env(safe-area-inset-bottom);
}

.nav-bar {
  height: 44px;
  background: #fff;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 16px;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 100;

  .title {
    font-size: 17px;
    font-weight: 500;
    color: #333;
  }

  .edit-btn {
    font-size: 14px;
    color: #2196f3;
    background: none;
    padding: 0;
    margin: 0;
    line-height: 1;

    &::after {
      display: none;
    }
  }
}

.filter-bar {
  position: fixed;
  top: 44px;
  left: 0;
  right: 0;
  z-index: 99;
  background: #fff;
  display: flex;
  padding: 12px 16px;
  border-bottom: 1px solid #f0f0f0;

  .filter-item {
    flex: 1;
    height: 36px;
    background: #f5f7fa;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 12px;
    margin: 0 6px;
    font-size: 14px;
    color: #666;

    .value {
      color: #333;
      margin: 0 4px;
    }

    .iconfont {
      font-size: 12px;
      color: #999;
    }
  }
}

.history-list {
  margin-top: 93px;
  height: calc(100vh - 93px);
  box-sizing: border-box;
}

.history-item {
  margin: 12px 16px 0;
  background: #fff;
  border-radius: 12px;
  padding: 16px;
  display: flex;
  align-items: center;

  .checkbox {
    margin-right: 12px;
    font-size: 20px;
    color: #2196f3;
  }

  .base-char {
    width: 44px;
    height: 44px;
    background: rgba(33, 150, 243, 0.05);
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 20px;
    color: #2196f3;
    margin-right: 12px;
  }

  .content {
    flex: 1;
    margin-right: 12px;

    .title-row {
      display: flex;
      align-items: center;
      margin-bottom: 4px;
    }

    .title {
      font-size: 16px;
      color: #333;
      margin-right: 8px;
    }

    .difficulty-tag {
      padding: 2px 6px;
      border-radius: 4px;
      font-size: 12px;

      &.difficulty-1 {
        background: rgba(76, 175, 80, 0.1);
        color: #4caf50;
      }

      &.difficulty-2 {
        background: rgba(255, 152, 0, 0.1);
        color: #ff9800;
      }

      &.difficulty-3 {
        background: rgba(244, 67, 54, 0.1);
        color: #f44336;
      }
    }

    .date {
      font-size: 12px;
      color: #999;
    }
  }

  .review-btn {
    height: 36px;
    background: rgba(33, 150, 243, 0.05);
    border-radius: 18px;
    color: #2196f3;
    font-size: 14px;
    display: flex;
    align-items: center;
    padding: 0 12px;

    &::after {
      display: none;
    }

    .iconfont {
      margin-right: 4px;
      font-size: 16px;
    }
  }
}

.loading,
.no-more {
  text-align: center;
  padding: 16px;
  color: #999;
  font-size: 14px;

  .iconfont {
    margin-right: 4px;
    animation: rotate 1s linear infinite;
  }
}

.edit-bar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background: #fff;
  border-top: 1px solid #f0f0f0;
  padding: 8px 16px;
  display: flex;
  align-items: center;
  justify-content: space-between;

  .select-all {
    display: flex;
    align-items: center;
    font-size: 14px;
    color: #666;

    .iconfont {
      margin-right: 4px;
      font-size: 20px;
      color: #2196f3;
    }
  }

  .delete-btn {
    height: 36px;
    background: #f44336;
    border-radius: 18px;
    color: #fff;
    font-size: 14px;
    padding: 0 20px;

    &::after {
      display: none;
    }
  }
}

.picker-content {
  background: #fff;
  border-radius: 12px 12px 0 0;
  overflow: hidden;

  .picker-header {
    height: 44px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 16px;
    border-bottom: 1px solid #f0f0f0;

    text {
      font-size: 16px;
      color: #333;
    }

    button {
      font-size: 14px;
      color: #2196f3;
      background: none;
      padding: 0;
      margin: 0;
      line-height: 1;

      &::after {
        display: none;
      }
    }
  }

  .picker-view {
    height: 200px;
  }

  .picker-item {
    line-height: 44px;
    text-align: center;
  }
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style> 